package com.nagat.ca;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class CodeHelper
{	
	public static byte[] Base64De(String base64_msg) throws IOException
	{
		BASE64Decoder base64De = null;
		try
		{
			base64De = new BASE64Decoder();
			return base64De.decodeBuffer(base64_msg.replace(" ", ""));
		}
		finally
		{
			base64De = null;
		}
	}
	
	public static String Base64En(byte[] byteMsg) throws IOException
	{
		BASE64Encoder base64En = null;
		try
		{
			base64En = new BASE64Encoder();
			return base64En.encode(byteMsg).replace("\r\n", "");
		}
		finally
		{
			base64En = null;
		}
	}
	
	public static byte[] DesDecrypt(byte[] byteMi, String strKey) 
				throws InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
	{
		return CodeHelper.Des(byteMi, strKey, Cipher.DECRYPT_MODE);
	}
	
	public static byte[] DesEncrypt(byte[] byteMi, String strKey) 
		throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException 
	{
		
		return CodeHelper.Des(byteMi, strKey, Cipher.ENCRYPT_MODE);
	}
	
	private static byte[] Des(byte[] byteData, String strKey, int opmode) 
			throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
	{
		Cipher cipher = null;
		try
		{
			DESKeySpec desKeySpec = new DESKeySpec(Tool.hexStringToByte(strKey));
    	    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    		Key key = keyFactory.generateSecret(desKeySpec);
    		
    		cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    		cipher.init(opmode, key);
    		
    		return cipher.doFinal(byteData);
		}
		finally
		{
			cipher = null;
		}	
	}
	
	public static void main(String[] args) throws Exception{
//		String strKey = "0102030405060708";
//		byte b[] = CodeHelper.DesDecrypt("aaa".getBytes(), strKey);
//		
//		String miwen = CodeHelper.Base64En(b);
//		System.out.println(miwen);
		
//		byte bb[] =CodeHelper.Base64De(miwen);
//		
//		String end = new String(CodeHelper.DesDecrypt(bb, strKey));
//		System.out.println(end);
		String str = new BASE64Encoder().encode("哈哈".getBytes());
		System.out.println(str);
		byte b[] = new BASE64Decoder().decodeBuffer(str);
		
		System.out.println(new String(b,"utf-8"));
		
		
		
	}
}
